package com.itmck.filterconfig;

import com.itmck.enums.DataSourceType;
import com.itmck.handler.DynamicDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/22 14:43
 **/
@Configuration
@MapperScan("com.itmck.dao")
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource primaryDateSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDateSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }


    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), primaryDateSource());
        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDateSource());
        return new DynamicDataSource(primaryDateSource(), targetDataSources);
    }
}